package com.ruoyi.rabbit.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.enums.wp.WpArticlesStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.rabbit.service.RabbitTimeJob;
import com.ruoyi.system.domain.WpKey;
import com.ruoyi.wp.domain.WpArticles;
import com.ruoyi.wp.domain.WpKeyArticlesLog;
import com.ruoyi.wp.domain.WpKeyCategory;
import com.ruoyi.wp.service.IWpArticlesService;
import com.ruoyi.wp.service.IWpKeyArticlesLogService;
import com.ruoyi.wp.service.IWpKeyCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.ArrayList;
import java.util.List;

@Service
public class RabbitTimeJobImpl implements RabbitTimeJob {
    @Autowired
    IWpKeyCategoryService iWpKeyCategoryService;
    @Autowired
    IWpKeyArticlesLogService iWpKeyArticlesLogService;
    @Autowired
    IWpArticlesService iWpArticlesService;
    @Override
    public void timeJobArticles(String json) {

        if (StringUtils.isNull(json)){
            System.out.println("MQ获取参数值错误，json参数为空！");
            return;
        }
        JSONObject data = JSON.parseObject(json);
        List<WpArticles> wpArticlesList = JSON.parseArray(data.getJSONArray("wpArticlesList").toJSONString(),WpArticles.class);
        WpKey wpKey = JSONObject.parseObject(data.getString("wpKey"),WpKey.class);
        Long userId = JSONObject.parseObject(data.getString("userId"),Long.class);

        //查询对应配置的分类
        WpKeyCategory tempWpKeyCategory = new WpKeyCategory();
        tempWpKeyCategory.setWpKeyId(wpKey.getId());
        tempWpKeyCategory.setUserId(userId);
        List<WpKeyCategory> wpKeyCategoryList = iWpKeyCategoryService.selectWpKeyCategoryList(tempWpKeyCategory);

        //轮询文章
        for (int i= 0 ;i<wpArticlesList.size();i++){
            WpArticles wpArticles = wpArticlesList.get(i);

            //分类判断校验配置
            for (int v = 0 ;v < wpKeyCategoryList.size();v++){
                WpKeyCategory wpKeyCategory = wpKeyCategoryList.get(v);
                if(wpKeyCategory.getDictCategoryId().equals(wpArticles.getCategoryId())){
                    JSONObject responseBody = this.sendPHP(wpKey, wpArticles, wpKeyCategory);
                    //插入PHP数据库返回成功结果
                    Long phpArticlesId = responseBody.getLong("post_id");

                    WpKeyArticlesLog wpKeyArticlesLog = new WpKeyArticlesLog();
                    wpKeyArticlesLog.setPhpArticlesId(phpArticlesId);
                    wpKeyArticlesLog.setWpArticlesId(wpArticles.getArticlesId());
                    wpKeyArticlesLog.setUserId(userId);
                    wpKeyArticlesLog.setStatus(1);
                    wpKeyArticlesLog.setWpKeyCategotyId(wpKeyCategory.getId());
                    wpKeyArticlesLog.setWpKeyId(wpKey.getId());

                    iWpKeyArticlesLogService.insertWpKeyArticlesLog(wpKeyArticlesLog);

                    //更新文章状态
                    wpArticles.setStatus(WpArticlesStatus.EXECUTED.getCode());
                    iWpArticlesService.updateWpArticles(wpArticles);
                }

            }

        }
    }

    JSONObject sendPHP(WpKey wpKey,WpArticles wpArticles,WpKeyCategory wpKeyCategory){

        // 创建一个RestTemplate实例
        RestTemplate restTemplate = new RestTemplate();

        // 构建请求URL和参数
        String url = wpKey.getSiteUrl();
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);

        // 构建请求体参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("api_token",wpKey.getApiToken());
        jsonObject.put("title",wpArticles.getTitle());
        //TODO 文章摘要，暂时不做
//                    jsonObject.put("post_excerpt",wpArticles.getTitle());
        //文章状态
        jsonObject.put("post_status","publish");

        //文章分类
        ArrayList<Long> arrayList = new ArrayList<>();
        arrayList.add(wpKeyCategory.getWpCategory());
        jsonObject.put("post_category",new JSONArray(arrayList));
        //文章内容
        jsonObject.put("content",wpArticles.getContent());
        //TODO 文章标签，暂时还没做
//                    jsonObject.put("tags_input",wpArticles.getContent());

        String requestBody = jsonObject.toString();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        System.out.println("请求发送PHP参数是");
        System.out.println(requestBody);
        // 发送POST请求并获取响应
        ResponseEntity<String> response = restTemplate.postForEntity(builder.toUriString(), requestEntity, String.class);

        // 打印响应
        System.out.println("响应内容: " + response);
        // 判断响应状态码
        if (response.getStatusCode() == HttpStatus.OK) {
            // 解析响应体内容
            JSONObject responseBody = JSON.parseObject(response.getBody());
            String code = responseBody.getString("code");
            String msg = responseBody.getString("msg");
            String postId = responseBody.getString("post_id");
            if (!"200".equals(code)) {
                throw new ServiceException("创建文章失败，错误信息: " + msg);
            }
            return responseBody;
        } else {
            throw new ServiceException("请求PHP失败，状态码: " + response.getStatusCode());
        }
    }

}
